import {designComponent, Fragment, getComponentCls, PropType, useClassCache} from "@peryl/react-compose";
import {Box, Button, Image} from "plain-design";
import {chunk} from "@peryl/utils/chunk";
import './page-card-list.scss';

export const PageCardList = designComponent({
  name: 'page-card-list',
  props: {
    data: { type: Array as PropType<any[]>, required: true },
    colNum: { type: Number, default: 7 },
    showEditButton: { type: Boolean, default: true },
    showCopyButton: { type: Boolean, default: true },
    showDeleteButton: { type: Boolean, default: true },
    editButtonText: { type: String },
    copyButtonText: { type: String },
    keyField: { type: String, default: 'id' },
    imageField: { type: String, default: 'image' },
    aspectRatio: { type: String, default: '3 / 4' },
  },
  emits: {
    onDelete: (item: any) => true,
    onEdit: (item: any) => true,
    onCopy: (item: any) => true,
  },
  setup({ props, event: { emit } }) {

    const classes = useClassCache(() => [
      getComponentCls('page-card-list'),
    ]);

    return () => (
      <div className={classes.value}>
        {chunk(props.data, props.colNum).map((subList, subIndex) => {
          return (
            <div key={subIndex} className="page-card-row" style={{ '--col': props.colNum, '--aspect-ratio': props.aspectRatio } as any}>
              {subList.map((item: any) => {
                if (typeof item === "function") {return <Fragment key="starter">{item()}</Fragment>;}
                return (
                  <Box key={item[props.keyField]} className="page-card-col">
                    <Image src={item[props.imageField]} width="100%" height="100%" previewOnClick={false} fit="cover" position="top left"/>
                    <Box className="resume-template-page-cover">
                      {props.showDeleteButton && (
                        <Box className="resume-template-page-cover-delete">
                          <Button icon="pi-close" mode="fill" size="mini" status="error" onClick={() => emit.onDelete(item)}/>
                        </Box>
                      )}
                      {props.showEditButton && (
                        <Button label={props.editButtonText} className="resume-template-page-cover-edit" mode="fill" onClick={() => emit.onEdit(item)}/>
                      )}
                      {props.showCopyButton && (
                        <Button label={props.copyButtonText} className="resume-template-page-cover-copy" mode="text" onClick={() => emit.onCopy(item)}/>
                      )}
                    </Box>
                  </Box>
                );
              })}
            </div>
          );
        })}
      </div>
    );
  },
});
